import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Vector;

public class TellstickDeviceFileInterface {

	private static String className = "TellstickDeviceFileInterface: ";

	public static Vector<Device> loadDevicesFromFile(
			String tellstickDeviceFilePath) {
		DEBUG("loadDevicesFromFile " + tellstickDeviceFilePath);

		Vector<Device> devices = new Vector<Device>();

		try {
			InputStream fis;
			BufferedReader br;
			String line;
			String idLine = "id = ";
			String nameLine = "name = ";

			int deviceID = 0;
			String deviceNameStr = "";

			int state = 0;

			fis = new FileInputStream(tellstickDeviceFilePath);
			br = new BufferedReader(new InputStreamReader(fis,
					Charset.forName("UTF-8")));

			while ((line = br.readLine()) != null) {

				if (line.contains(idLine)) {
					if (state != 0) {
						devices.add(new Device(deviceID, ""));
						state = 0;
					} else {
						state = 1;
					}

					deviceID = Integer.parseInt(line.substring(
							line.indexOf(idLine) + idLine.length(),
							line.length()));
					DEBUG("Device ID: " + deviceID);
				}

				if (line.contains(nameLine) && state == 1) {
					deviceNameStr = line.substring(line.indexOf("\"") + 1,
							line.lastIndexOf("\""));
					DEBUG("Device name: " + deviceNameStr);
					state = 2;
				}

				if (state == 2) {
					devices.add(new Device(deviceID, deviceNameStr));
					state = 0;
				}
			}

			br.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return devices;
	}

	private static void DEBUG(String debugString) {
		Macros.DEBUG(className + debugString);
	}
}
